package comp9417;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

/**
 * Created by huy on 20/05/14.
 */
public class Dataset {
    private final int numberOfAttributes;

    public List<DataPoint> getDatapoints() {
        return datapoints;
    }

    private final List<DataPoint> datapoints = new ArrayList<DataPoint>();
    private final Attribute[] attributes;

    public Dataset(Attribute[] attributes) {
        this.numberOfAttributes = attributes.length;
        this.attributes = attributes;
    }

    public void addPoint(DataPoint dataPoint) {
        datapoints.add(dataPoint);
    }

    public Attribute[] getAttributes() {
        return attributes;
    }

    public int getAttributeIndex(String attribute) {
        for (int index = 0; index < attributes.length; index++) {
            if (attributes[index].name.equals(attribute)) {
                return index;
            }
        }
        return -1;
    }

    public int getNumberOfAttributes() {
        return numberOfAttributes;
    }

    public Dataset randomize() {
        Random random = new Random(System.currentTimeMillis());
        Dataset newDataSet = new Dataset(attributes);
        for (DataPoint dataPoint : datapoints) {
            int j = random.nextInt(newDataSet.datapoints.size() + 1);
            if (j == newDataSet.datapoints.size()) {
                newDataSet.datapoints.add(dataPoint);
            } else {
                newDataSet.datapoints.add(newDataSet.datapoints.get(j));
                newDataSet.datapoints.set(j, dataPoint);
            }
        }
        return newDataSet;
    }

    public Attribute getAttribute(String classifierAttribute) {
        for (Attribute attribute : attributes) {
            if (attribute.name.equals(classifierAttribute)) {
                return attribute;
            }
        }
        throw new RuntimeException("No attribute with name " + classifierAttribute + " found.");
    }

    public Iterable<Fold> createFolds(final int k) {
        return new Iterable<Fold>() {
            @Override
            public Iterator<Fold> iterator() {
                return new FoldIterator(Dataset.this, k);
            }
        };
    }
}
